package com.lenovo.smarttraffic.view;

import android.content.Context;
import android.os.Handler;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.AbsListView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.lenovo.smarttraffic.R;


public class RefreshListView extends ListView implements AbsListView.OnScrollListener {
    private static final String TAG = "RefreshListView";

    /**
     *下拉刷新的控件放置的地方
     */
    private View mHeaderView;

    /**
     * 列表的高度
     */
    private int mHeaderViewHeight;

    /**
     * 按下的y轴距离
     */
    private float dowY;
    /**
     * 移动的y轴距离
     */
    private float moveY;

    /**
     * 下拉刷新
     */
    public static final int PULL_TO_REFRESH = 0;
    /**
     * 释放刷新
     */
    public static final int RELEASE_REFRESH = 1;
    /**
     * 释放刷新
     */
    public static final int REFRESHING = 2;
    /**
     * 刷新完成
     */
    public static final int DONE = 3;
    /**
     * 当前刷新模式
     */
    private int currentState = PULL_TO_REFRESH;
    /**
     * 箭头向上动画
     */
    private RotateAnimation rotateUpAnim;
    /**
     * 箭头向下动画
     */
    private RotateAnimation rotateDownAnim;
    /**
     * 箭头图片
     */
    private ImageView ivArrow;

    private ProgressBar pbProgress;

    private TextView tvTitle;

    private OnRefreshListener mListener;


    /**
     * 构造器
     * @param context
     */
    public RefreshListView(Context context) {
        super(context);
        init();
    }
    public RefreshListView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public RefreshListView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    /**
     * 初始化头布局, 脚布局
     * 滚动监听
     */
    private void init() {
        initHeaderView();
        initAnimation();
        //listView不支持嵌套滑动onNestSCroll
        setOnScrollListener(this);
    }

    /**
     * 初始化头布局
     */
    private void initHeaderView() {
        mHeaderView = View.inflate(getContext(), R.layout.layout_header_list, null);
        ivArrow = (ImageView) mHeaderView.findViewById(R.id.iv_arrow);
        pbProgress = (ProgressBar) mHeaderView.findViewById(R.id.pb_progress);
        tvTitle = (TextView) mHeaderView.findViewById(R.id.tv_title);
        /*提前手动测量宽高*/
        mHeaderView.measure(0, 0);
        /*获取自身高度*/
        mHeaderViewHeight = mHeaderView.getMeasuredHeight();
        /*设置内边距，可以隐藏布局  -自身高度*/
        mHeaderView.setPadding(0, -mHeaderViewHeight, 0, 0);
        addHeaderView(mHeaderView);
    }

    /**
     * 初始化头布局的动画
     */
    private void initAnimation() {
        // 向上转, 围绕着自己的中心, 逆时针旋转0 -> -180.
        rotateUpAnim = new RotateAnimation(0f, -180f,
                Animation.RELATIVE_TO_SELF, 0.5f,
                Animation.RELATIVE_TO_SELF, 0.5f);
        rotateUpAnim.setDuration(300);
        // 动画停留在结束位置
        rotateUpAnim.setFillAfter(true);
        // 向下转, 围绕着自己的中心, 逆时针旋转 -180 -> -360
        rotateDownAnim = new RotateAnimation(-180f, -360f,
                Animation.RELATIVE_TO_SELF, 0.5f,
                Animation.RELATIVE_TO_SELF, 0.5f);
        rotateDownAnim.setDuration(300);
        rotateDownAnim.setFillAfter(true);
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        /*判断滑动距离，给Header设置paddingTop*/
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                //记录按下的y坐标
                dowY = ev.getRawY();
                break;
            case MotionEvent.ACTION_MOVE:
                moveY = ev.getRawY();
                // 如果是正在刷新中, 不执行move后的代码
                if (currentState == REFRESHING) {
                    return super.onTouchEvent(ev);
                }
                // 移动的偏移量
                float offset = (moveY - dowY) / 4;
                // 只有 偏移量>0---->下拉, 并且当前第一个可见条目索引是0, 才放大头部
                if (offset > 0 && getFirstVisiblePosition() == 0) {
                    //int paddingTop = -自身高度 + 偏移量;决定下拉高度
                    int paddingTop = (int) (-mHeaderViewHeight + offset);
                    if (paddingTop >= 0 && currentState != RELEASE_REFRESH) {
                        //下拉的高度大于item的高度，头布局完全显示
                        // 切换成释放刷新模式
                        currentState = RELEASE_REFRESH;
                        updateHeader();
                    } else if (paddingTop < 0 && currentState != PULL_TO_REFRESH) {
                        // 头布局不完全显示
                        // 切换下拉刷新模式
                        currentState = PULL_TO_REFRESH;
                        updateHeader();
                    }
                    mHeaderView.setPadding(0, paddingTop, 0, 0);
                    // 当前事件被我们处理并消费
                    return true;
                }
                break;
            case MotionEvent.ACTION_UP:
                // 根据刚刚设置状态
                if (currentState == PULL_TO_REFRESH) {
                    //- paddingTop < 0 不完全显示, 恢复
                    mHeaderView.setPadding(0, -mHeaderViewHeight, 0, 0);
                } else {
                    //- paddingTop >= 0 完全显示, 执行正在刷新...
                    mHeaderView.setPadding(0, 0, 0, 0);
                    invalidate();
                    currentState = REFRESHING;
                    updateHeader();

                }
                break;
            default:
                break;

        }
        return super.onTouchEvent(ev);
    }

    /**
     * 根据状态更新头布局内容
     */
    private void updateHeader() {
        switch (currentState) {
            //切换成下拉刷新
            case PULL_TO_REFRESH:
                //切换动画，改标题
                ivArrow.startAnimation(rotateDownAnim);
                tvTitle.setText("下拉刷新");
                break;
            //切换成释放刷新
            case RELEASE_REFRESH:
                //切换动画，改标题
                ivArrow.startAnimation(rotateUpAnim);
                tvTitle.setText("释放刷新");
                break;
            //切换成正在刷新
            case REFRESHING:
                //切换动画改标题
                ivArrow.clearAnimation();
                ivArrow.setVisibility(INVISIBLE);
                pbProgress.setVisibility(VISIBLE);
                tvTitle.setText("正在刷新");
                if (mListener != null) {
                    mListener.onRefresh();
                }
                break;
            case DONE:
                ivArrow.setVisibility(VISIBLE);
                pbProgress.setVisibility(INVISIBLE);
                ivArrow.setImageResource(R.mipmap.compete);
                tvTitle.setText("刷新完成");
                break;
            default:
                break;
        }
    }

    /**
     * 刷新结束恢复界面效果
     */
    public void onRefreshComplete() {
        currentState = DONE;
        updateHeader();
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                mHeaderView.setPadding(0, -mHeaderViewHeight, 0, 0);
                //回到最初是的状态
                currentState = PULL_TO_REFRESH;
                ivArrow.setImageResource(R.mipmap.down_arrow);
                tvTitle.setText("下拉刷新");
                ivArrow.setVisibility(VISIBLE);
                pbProgress.setVisibility(INVISIBLE);
            }
        }, 1000);


    }




    public void setRefreshListener(OnRefreshListener mListener) {
        this.mListener = mListener;
    }


    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {

    }


    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {


    }

    public interface OnRefreshListener {
        void onRefresh(); // 下拉刷新
    }
}

